import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'

const useViewStore = defineStore('login', () => {
  const user = ref(null)
  const data = ref(null)
  const status = ref(0)

  const login = ({ username, password }) => {
    return new Promise((resolve, reject) => {
      axios
        .post('api/login.php?output=login', { username, password })
        .then((response) => {
          if (response.data.status == 1) {
            data.value = response.data.user
            user.value = {
              name: response.data.user.name,
              number: response.data.user.number
            }
            status.value = 1
          } else {
            // ???
          }
          console.log('login', response.data)
          resolve(response.data)
        })
        .catch((error) => {
          console.error('login', error)
          reject(error)
        })
    })
  }

  const logout = () => {
    user.value = null
    data.value = null
    status.value = 0
  }

  return { user, data, status, login, logout }
})

export default useViewStore
